package processor;

import adapter.Adapter;
import server.Request;
import server.Response;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @ClassName : Processor
 * @Description : Processor用于将Endpoint接收到的Socket封装成Request，用来实现HTTP协议的
 * @Author : zhangxiaohai
 * @Date: 2021-06-24 08:28
 */
public class Processor implements Runnable{
    private final Socket socket;
    private final Adapter adapter;

    public Processor(Socket socket, Adapter adapter) {
        this.socket = socket;
        this.adapter = adapter;
        System.out.println(this.getClass().getName() + " recv a request " + socket.getLocalAddress().toString() + " port:" + socket.getPort());
    }

    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            Request request = new Request(inputStream);
            Response response = new Response(outputStream);

            adapter.service(request, response);

            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
